#include "timeslice.h"
#include <string.h>
#include <stdio.h>


static LIST_HEAD(timeslice_task_list);

void timeslice_exec()
{
    ListObj* node;
    TimesilceTaskObj* task;

    list_for_each(node, &timeslice_task_list)
    {
           
        task = list_entry(node, TimesilceTaskObj, timeslice_task_list);
        if (task->is_run == TASK_RUN)
        {
            task->task_hdl();
            
            task->is_run = TASK_STOP;
        }
    }
}

void timeslice_tick()
{
    ListObj* node;
    TimesilceTaskObj* task;

    list_for_each(node, &timeslice_task_list)
    {
        task = list_entry(node, TimesilceTaskObj, timeslice_task_list);
        if (task->timer != 0)
        {
            task->timer--;
            if (task->timer == 0)
            {
                task->is_run = TASK_RUN;
                task->timer = task->time_interval;
            }
        }
    }
}

unsigned int timeslice_get_task_num()
{
    return list_len(&timeslice_task_list);
}

void timeslice_print_all_tasks_name(void)
{
  ListObj* node;
  TimesilceTaskObj* task;

  list_for_each(node, &timeslice_task_list)
  {
      task = list_entry(node, TimesilceTaskObj, timeslice_task_list);
      printf("%s.\n", task->task_name);
  }  
}

void timeslice_task_init(TimesilceTaskObj* obj, void (*task_hdl)(void), unsigned int id, const char *task_name, unsigned int time_interval)
{
    obj->id = id;
    if(task_name)
    {
      memset(obj->task_name, 0x0, NAME_LEN);
      memcpy(obj->task_name, task_name, NAME_LEN);
    }
    
    obj->is_run = TASK_STOP;
    obj->task_hdl = task_hdl;
    obj->timer = time_interval;
    obj->time_interval = time_interval;
}

void timeslice_task_add(TimesilceTaskObj* obj)
{
    list_insert_before(&timeslice_task_list, &obj->timeslice_task_list);
}

void timeslice_task_del(TimesilceTaskObj* obj)
{
    if (timeslice_task_isexist(obj))
        list_remove(&obj->timeslice_task_list);
    else
        return;
}


unsigned char timeslice_task_isexist(TimesilceTaskObj* obj)
{
    unsigned char isexist = 0;
    ListObj* node;
    TimesilceTaskObj* task;

    list_for_each(node, &timeslice_task_list)
    {
        task = list_entry(node, TimesilceTaskObj, timeslice_task_list);
        if (obj->id == task->id)
            isexist = 1;
    }

    return isexist;
}

unsigned int timeslice_get_task_time_interval(TimesilceTaskObj* obj)
{
    return obj->time_interval;
}

unsigned int timeslice_get_task_id(TimesilceTaskObj* obj)
{
    return obj->id;
}

char *timeslice_get_task_name(TimesilceTaskObj* obj)
{
    if(obj->task_name)
      return obj->task_name;
    
    return "NO Name";
}

unsigned char timeslice_get_task_status(TimesilceTaskObj* obj)
{
    return obj->is_run;
}

unsigned int timeslice_get_task_timer_left(TimesilceTaskObj* obj)
{
    return obj->timer;
}



